package com.example.sanguogameserver.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sanguogameserver.entity.AttackTask;
import com.example.sanguogameserver.entity.Player;
import com.example.sanguogameserver.entity.PlayerGeneral;
import com.example.sanguogameserver.entity.Territory;
import com.example.sanguogameserver.enums.BattleEnum;
import com.example.sanguogameserver.enums.EnableEnum;
import com.example.sanguogameserver.enums.ProcessEnum;
import com.example.sanguogameserver.mapper.AttackTaskMapper;
import com.example.sanguogameserver.request.AttackCreateTaskReq;
import com.example.sanguogameserver.request.PlayerGeneralIdIndex;
import com.example.sanguogameserver.response.AttackTaskResp;
import com.example.sanguogameserver.util.AuthUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 攻打任务 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-05-15
 */
@Service
public class AttackTaskService extends ServiceImpl<AttackTaskMapper, AttackTask> implements IService<AttackTask> {
    @Autowired
    private PlayerGeneralService playerGeneralService;
    @Autowired
    private TerritoryService territoryService;
    @Autowired
    private PlayerService playerService;

    @Transactional
    public void attack(AttackCreateTaskReq attackCreateTaskReq) {
        // 校验
        // 查找所有武将,是否都是可以攻击
        List<PlayerGeneral> playerGenerals = new ArrayList<>();
        for (PlayerGeneralIdIndex playerGeneralId : attackCreateTaskReq.getPlayerGenerals()) {
            PlayerGeneral playerGeneral = playerGeneralService.getById(playerGeneralId.getId());
            Assert.isTrue(playerGeneral.getTerritoryId() == null, StrUtil.format("{}已驻扎", playerGeneral.getGeneralName()));
            Assert.isTrue(playerGeneral.getAttackTaskId() == null, StrUtil.format("{}已有攻击任务", playerGeneral.getGeneralName()));
            playerGenerals.add(playerGeneral);
        }
        Territory territory = territoryService.getById(attackCreateTaskReq.getBeAttackTerritoryId());
        Assert.isTrue(territory.getPlayId() != null);

        AttackTask attackTask = new AttackTask();
        attackTask.setArrivalTime(attackCreateTaskReq.getArrivalTime());
        // 预约战斗时间
        LocalDateTime prepareAttackTime = LocalDateTimeUtil.offset(attackCreateTaskReq.getArrivalTime(), -15, ChronoUnit.MINUTES);

        attackTask.setPrepareAttackTime(prepareAttackTime);
        attackTask.setProcess(ProcessEnum.False);
        attackTask.setAttackPlayerId(AuthUtil.getCurrPlayerId());
        attackTask.setBeAttackPlayerId(territory.getPlayId());
        attackTask.setBeAttackTerritoryId(attackCreateTaskReq.getBeAttackTerritoryId());
        attackTask.setCreateTime(LocalDateTime.now());
        attackTask.setIsBattle(BattleEnum.didnTStart);
        attackTask.setAttackIsEnter(EnableEnum.False);
        attackTask.setBeAttackIsEnter(EnableEnum.False);
        save(attackTask);
        playerGeneralService.batchSetAttackTaskId(attackCreateTaskReq.getPlayerGenerals(), attackTask.getId());
    }

    public List<AttackTaskResp> listRecord() {
        return  baseMapper.listRecord(AuthUtil.getCurrPlayerId());
    }



    public void updateAttackTaskStatus() {
        // 未开始战斗状态,并且时间到了
        LocalDateTime now = LocalDateTime.now();
        LocalDateTimeUtil.offset(now,-30, ChronoUnit.MINUTES);
        List<AttackTask> didnAttackTasks = baseMapper.selectTodoAttackTask(now, BattleEnum.didnTStart);
        if (CollectionUtil.isNotEmpty(didnAttackTasks)) {
            lambdaUpdate()
                    .set(AttackTask::getIsBattle, BattleEnum.todoBattle)
                    .in(AttackTask::getId, didnAttackTasks.stream().map(AttackTask::getId).toList())
                    .update();
        }
       /* List<AttackTask> todoAttackTasks = baseMapper.selectTodoAttackTask(LocalDateTime.now(), BattleEnum.todoBattle);
        if (CollectionUtil.isNotEmpty(todoAttackTasks)) {
            lambdaUpdate()
                    .set(AttackTask::getIsBattle, BattleEnum.inBattle)
                    .in(AttackTask::getId, todoAttackTasks.stream().map(AttackTask::getId).toList())
                    .update();
        }*/
    }

    public void enterAttackTask(Integer id) {
        AttackTask attackTask = getById(id);
        Player player = playerService.getById(AuthUtil.getCurrPlayerId());
        player.setAttackTaskId(id);
        if (attackTask.getAttackPlayerId().equals(AuthUtil.getCurrPlayerId())) {
            attackTask.setAttackIsEnter(EnableEnum.True);
        } else if (attackTask.getBeAttackPlayerId().equals(AuthUtil.getCurrPlayerId())) {
            attackTask.setBeAttackIsEnter(EnableEnum.True);
        } else {
            throw new IllegalArgumentException("异常");
        }
        updateById(attackTask);
        playerService.updateById(player);
    }
}
